package control;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.AbstractAction;
import javax.swing.KeyStroke;

import view.LibraryMainJFrame;
import view.NewLoanJDialog;
import view.components.Icons;
import view.models.CustomerStatus;


import domain.Copy;
import domain.Customer;
import domain.Library;
import domain.Loan;

@SuppressWarnings("serial")
public class NewLoanAction extends AbstractAction implements Observer {
	private LibraryMainJFrame mainFrame;
	private Copy copy;
	private Customer customer;

	public NewLoanAction(LibraryMainJFrame frame) {
		super("Neue Ausleihe", Icons.LOAN_ADD);
		mainFrame = frame;

		putValue(ACCELERATOR_KEY,
				KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
		putValue(MNEMONIC_KEY, KeyEvent.VK_N);
	}

	public NewLoanAction(LibraryMainJFrame frame, Customer customer) {
		this(frame);
		this.customer = customer;
		Library.getInstance().addObserver(this);
		updateStatus();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		NewLoanJDialog dialog;
		if (copy != null) {
			dialog = new NewLoanJDialog(mainFrame, copy);
		} else if (customer != null) {
			dialog = new NewLoanJDialog(mainFrame, customer);
		} else {
			dialog = new NewLoanJDialog(mainFrame);
		}
		dialog.setVisible(true);
	}

	@Override
	public void update(Observable o, Object arg1) {
		if(customer != null && arg1 instanceof Loan || o instanceof Loan){
			updateStatus();
		}
	}

	private void updateStatus() {
		for(Loan l : Library.getInstance().getCustomerCurrentLoans(customer)){
			l.addObserver(this);
		}
		setEnabled(CustomerStatus.getInstanceOf(customer).canLend());
	}

}
